package com.jiangyao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiangyao.dao.IIntegralLogDao;
import com.jiangyao.dao.IUserDao;
import com.jiangyao.model.dto.IntegralLogVo;
import com.jiangyao.model.entity.IntegralLog;
import com.jiangyao.model.entity.User;
import com.jiangyao.service.IntegralLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 积分流水日志 服务实现类
 * </p>
 *
 * @author yangyongchaun
 * @since 2020-09-01
 */
@Service
public class IntegralLogServiceImpl extends BaseServiceImpl<IIntegralLogDao, IntegralLog> implements IntegralLogService {

	@Autowired
	private IUserDao userDao;

	@Autowired
	private IIntegralLogDao integralLogDao;

	@Override
	public Integer getIntegralSumByType(Integer type) {
		IntegralLogVo log = new IntegralLogVo();
		log.setSourceType(type);
		log.setUserId(getLoginApiUserId());
		log.setStatus(1);
		return integralLogDao.getIntegralSum(log);
	}

	@Override
	public Integer getIntegralSumByTypeList(List<Integer> typeList) {
		IntegralLogVo log = new IntegralLogVo();
		log.setSourceTypeList(typeList);
		log.setUserId(getLoginApiUserId());
		log.setStatus(1);
		return integralLogDao.getIntegralSum(log);
	}

	@Async
	@Override
	public void saveLogAndUpdateUserIntegral(boolean allowRepeat, IntegralLog integralLog) {

		// 不允许重复
		if (!allowRepeat) {
			// 查询已存在 相同积分来源、积分来源关联ID的记录条数
			QueryWrapper<IntegralLog> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("user_id", integralLog.getUserId()).eq("source_type", integralLog.getSourceType())
					.eq("source_id", integralLog.getSourceId()).eq("status", 1);
			int count = this.count(queryWrapper);
			// 存在相同记录，直接返回
			if (count > 0) {
				return;
			}
		}

		integralLog.setCreateTime(new Date());
		integralLog.setStatus(1);
		this.save(integralLog);
		UpdateWrapper<User> uw = new UpdateWrapper<>();
		uw.eq("user_id", integralLog.getUserId());
		uw.setSql(" integral_num = integral_num + " + integralLog.getIntegralNum());
		userDao.update(null, uw);
	}

	@Async
	@Override
	public void saveLogAndUpdateUserIntegral(boolean allowRepeat,Integer userId, Integer sourceType, String sourceId, Integer integralNum, String remark) {
		IntegralLog integralLog = IntegralLog.builder().userId(userId).sourceType(sourceType).sourceId(sourceId)
				.integralNum(integralNum).remark(remark).build();
		this.saveLogAndUpdateUserIntegral(allowRepeat, integralLog);
	}

}
